// * Form组件
<template>
  <form>
    <slot></slot>
  </form>
</template>

<script>
export default {
  name: 'Form',

  provide() {
    return {
      form: this,
    }
  },

  components: {},

  props: {
    model: {
      type: Object,
    }, // 数据
    rules: {
      type: Object,
    }, // 验证规则
    hideRequiredMark: {
      type: Boolean,
      default: false,
    }, // 隐藏 “*” 标记
  },

  data() {
    return {
      formItems: [], // 存放formItem实例
    }
  },

  computed: {},

  watch: {},

  created() {
    // 监听formItem实例行为
    this.$on('on-form-item-add', instance => this.formItems.push(instance))
    this.$on('on-form-item-remove', instance => {
      this.formItems = this.formItems.filter(item => item !== instance)
    })
  },

  mounted() {},

  methods: {
    // * 重置表单
    resetFields() {
      this.formItems.forEach(formItem => formItem.resetField())
    },

    // * 校验整个表单
    validate(callback) {
      return new Promise((resolve, reject) => {
        let valid = true
        let count = 0

        this.formItems.forEach(field => {
          field
            .validate('')
            .catch(() => {
              valid = false
            })
            .finally(() => {
              if (++count === this.formItems.length) {
                if (callback) callback(valid)
                resolve(valid)
              }
            })
        })
      })
    },

    // * 单独校验指定表单
    validateField(prop, callback) {
      const field = this.formItems.filter(field => field.prop === prop)
      if (!field) {
        throw new Error(
          '[skyui warn]: must call validateField with valid prop string!'
        )
      }

      field.validate()
    },
  },
}
</script>

<style lang="less" scoped></style>
